package com.huangym

import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import java.util.concurrent.TimeUnit

fun firstCoroutineDemo0() {
    launch(CommonPool) {
        delay(3000L, TimeUnit.MILLISECONDS)
        println("Hello,")
    }
    println("World!")
    Thread.sleep(5000L)
}

/**
 * 使用join，让两个协程参与到主线程的时间顺序里
 */
fun testJoinCoroutine() = runBlocking {
    val c1 = launch(CommonPool) {
        println("C1 Thread: ${Thread.currentThread()}")
        println("C1 Start")
        delay(3000)
        println("C1 World! 1")
    }
    val c2 = launch(CommonPool) {
        println("C2 Thread: ${Thread.currentThread()}")
        println("C2 Start")
        delay(5000)
        println("C2 World! 2")
    }
    println("Main Thread: ${Thread.currentThread()}")
    println("Hello, ")
    println("c1 is active: ${c1.isActive}   isCompleted: ${c1.isCompleted}")
    println("c2 is active: ${c2.isActive}   isCompleted: ${c2.isCompleted}")
    c1.join()
    println("Hi, ")
    println("c1 is active: ${c1.isActive}   isCompleted: ${c1.isCompleted}")
    println("c2 is active: ${c2.isActive}   isCompleted: ${c2.isCompleted}")
    c2.join()
    println("c1 is active: ${c1.isActive}   isCompleted: ${c1.isCompleted}")
    println("c2 is active: ${c2.isActive}   isCompleted: ${c2.isCompleted}")
}

//fun testCancellation() = runBlocking {
fun main(args: Array<String>) = runBlocking {
    val job = launch(CommonPool) {
        repeat(1000) { i ->
            println("I'm sleeping $i ... CurrentThread: ${Thread.currentThread()}")
            delay(500)
        }
    }
    delay(1300)
    println("CurrentThread: ${Thread.currentThread()}")
    println("Job is alive: ${job.isActive}  Job is completed: ${job.isCompleted}")
    val b1 = job.cancel()
    println("job cancel: $b1")
    delay(1300)
    println("Job is alive: ${job.isActive}  Job is completed: ${job.isCompleted}")

    val b2 = job.cancel()
    println("job cancel: $b2")
    println("main: Now I can quit")
}